import {
    Box,
    CircularProgress,
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableRow,
    Typography
} from '@mui/material';
import React, { useEffect, useState } from 'react';

import DisbursementManager from '../../api/disbursement/disbursement-manager';
import DisbursementType from '../../api/disbursement/disbursement-type';
import PayrollGroup from '../../api/payroll-group/payroll-group';
import PayrollGroupManager from '../../api/payroll-group/payroll-group-manager';
import MainLayout from '../../components/HOCs/main-layout';
import PayrollGroupsPopup from '../../components/payroll-groups/payroll-groups-popup';
import PayrollGroupsRow from '../../components/payroll-groups/payroll-groups-row';
import { GFSButton } from '../../components/shared/button/gfs-button';
import GFSTable from '../../components/shared/tables/gfs-table';
import { useInfiniteScroll } from '../../hooks/infinitive-scroll';
import { useLoadPayrollGroups } from '../../hooks/payroll-groups-load-more';

export default function PayrollGroupPage() {
    const [pageLoading, setPageLoading] = useState(true);

    const { loading, items, hasNextPage, error, loadMore } = useLoadPayrollGroups();

    const [sentryRef] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 400px 0px'
    });

    useEffect(() => {
        const load = async () => {
            await loadMore();
            setPageLoading(false);
        };

        load().then();
    }, []);

    const [openPopup, setOpenPopup] = useState<boolean>(false);
    const [groups, setGroups] = useState<Array<PayrollGroup>>(null);
    const [types, setTypes] = useState<Array<DisbursementType>>([]);

    useEffect(() => {
        PayrollGroupManager.getAll().then((groups: Array<PayrollGroup>) => {
            setGroups(groups);
        });

        DisbursementManager.getTypes().then((types: Array<DisbursementType>) => {
            setTypes(types);
        });
    }, []);

    useEffect(() => {
        setGroups(items);
    }, [items]);

    const onPopupClick = () => {
        setOpenPopup(true);
    };

    const onPopupClose = (payrollGroup?: PayrollGroup) => {
        if (payrollGroup) {
            groups.unshift(payrollGroup);
            setGroups(groups);
        }

        setOpenPopup(false);
    };

    return (
        <MainLayout>
            <Box sx={{ p: 6 }}>
                <Box className="d-flex justify-content-between">
                    <Typography variant="h2" color="white" sx={{ pb: 3 }}>
                        Payroll Group
                    </Typography>
                    <GFSButton onClick={onPopupClick}>Add Payroll Group</GFSButton>
                </Box>

                {pageLoading ? (
                    <Typography variant="h6" color="white">
                        Loading...
                    </Typography>
                ) : (
                    <Box sx={{ pb: 4 }}>
                        {!error ? (
                            <>
                                {groups?.length > 0 && (
                                    <GFSTable>
                                        <Table
                                            sx={{ minWidth: 650 }}
                                            aria-label="Disbursement List"
                                        >
                                            <TableHead>
                                                <TableRow>
                                                    <TableCell>Group Name</TableCell>
                                                    <TableCell align="center">Members</TableCell>
                                                    <TableCell align="center">Group Type</TableCell>
                                                    <TableCell align="center">
                                                        Monthly Payout Dates
                                                    </TableCell>
                                                    <TableCell align="center">
                                                        Member Share
                                                    </TableCell>
                                                    <TableCell align="center">
                                                        Minimum Payout Amount
                                                    </TableCell>
                                                </TableRow>
                                            </TableHead>
                                            <TableBody>
                                                {groups &&
                                                    groups.map((group: PayrollGroup) => (
                                                        <PayrollGroupsRow
                                                            key={group.id}
                                                            group={group}
                                                            types={types}
                                                        />
                                                    ))}
                                            </TableBody>
                                        </Table>
                                    </GFSTable>
                                )}
                                {!loading && (!groups || !groups.length) && (
                                    <Typography className="text-white mt-4">
                                        No payroll group yet...
                                    </Typography>
                                )}
                                {sentryRef && (loading || hasNextPage) && (
                                    <Box
                                        display="flex"
                                        justifyContent="center"
                                        alignItems="center"
                                        sx={{ pt: 4 }}
                                    >
                                        <CircularProgress
                                            ref={sentryRef}
                                            sx={{ color: '#ffffff' }}
                                        />
                                    </Box>
                                )}
                            </>
                        ) : error?.message ? (
                            <Typography className="mt-4" sx={{ color: 'var(--color-negative)' }}>
                                Something went wrong!
                            </Typography>
                        ) : (
                            <Typography className="text-white mt-4">
                                No payroll group yet...
                            </Typography>
                        )}
                    </Box>
                )}
            </Box>

            <PayrollGroupsPopup open={openPopup} onClose={onPopupClose} />
        </MainLayout>
    );
}
